package com.student.dao;

import com.student.util.ReflectUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * Created by zhudong on 2016/9/12.
 */
public class BaseDao<T> implements CRUDSupport<T> {

    private Class<T> entityClass;

    @Autowired
    private SessionFactory sessionFactory;

    public BaseDao() {
//        private Class<T> entityClass;
        entityClass = ReflectUtil.getClassGenricType(getClass());
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public T get(Serializable id){
        return (T)getSession().get(entityClass,id);
    }

    public void save(T t){
        getSession().save(t);
    }

    public void delete(Serializable id){
        getSession().delete(get(id));
    }

    public void update(T t){
        getSession().update(t);
    }

    public List<T> getAll(){
        String hql = "from "+entityClass.getSimpleName();
        return getSession().createQuery(hql).list();
    }
}
